package com.bitoon.web.captcha;

import java.awt.*;
import java.awt.image.*;

public class Captcha extends javax.servlet.http.HttpServlet {

    private int WIDTH = 126;
    private int HEIGHT = 71;
    private int NUM = 8;
    // Primer color de degradado:
    private int[] rgb1 = {0, 100, 100};
    // Segundo color de degradado:
    private int[] rgb2 = {0, 255, 255};

    private void draw(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {
        try {
            // Fuente y Colores:
            Font font = new Font("Georgia", Font.BOLD, 14);
            Color c1 = new Color(rgb1[0], rgb1[1], rgb1[2]);
            Color c2 = new Color(rgb2[0], rgb2[1], rgb2[2]);
            // Creamos la imagen:
            BufferedImage bimage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bimage.createGraphics();
            // Establecemos la gradiente del fondo:
            GradientPaint gp = new GradientPaint(0, 0, c1, 0, HEIGHT, c2);
            g.setPaint(gp);
            g.fillRect(0, 0, WIDTH, HEIGHT);
            // Ponemos la fuente y el color del texto:
            g.setFont(font);
            g.setColor(c2);
            // Escribimos el texto, variando la altura de los caracteres:
            //char[] text = getText(NUM);

            String ALFABETO = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            int NUM_LETRAS = 7;
            String text = "";

            for (int x=0; x<NUM_LETRAS; x++) {
                text+=ALFABETO.charAt((int)(Math.random()*ALFABETO.length()));
            }

            // Almacenamos el texto en la sesion, para su posterior comprobacion

            request.getSession().setAttribute("textoCaptcha", text);

            java.util.Random rand;
            int y;
            for (int i = 0; i < text.length(); i++) {
                rand = new java.util.Random(System.currentTimeMillis());
                y = (int)(Math.random()*55)+10;
                g.drawChars(text.toCharArray(), i, 1, 15 * (i + 1), y);
            }
            // Mostramos la imagen:
            g.dispose();
            response.setContentType("image/png");
            java.io.OutputStream outputStream = response.getOutputStream();
            javax.imageio.ImageIO.write(bimage, "png", outputStream);
            outputStream.close();
        } catch (Exception e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }

    public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {
        draw(request, response);
    }

    public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {
        draw(request, response);
    }
    
}
